/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Net.Mail;

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author mohamed.tarek
 */
public class MSJ_SendMail {

    private static String host;
    private static int port;

    /**
     *
     * @param subject
     * @param content
     * @param toAddress
     * @param hostname : choose from enumeration MSJ_SendHost.
     * @return Boolean : if send is Ok it send true else send false.
     */
    public static boolean sendingMessage(MSJ_Mail maildata,
            String toAddress, MSJ_MailHost hostname) {
        try {
            if (hostname.equals(MSJ_MailHost.GoogleMail)) {
                host = "smtp.gmail.com";
                port = 587;
            } else if (hostname.equals(MSJ_MailHost.YahooMail)) {
                host = "smtp.mail.yahoo.com";
                port = 587;
            }

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");

            Session session = Session.getInstance(props);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, port, maildata.getUsername(), maildata.getPassword());

            Address[] addresses = InternetAddress.parse(toAddress);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(maildata.getUsername()));
            message.setRecipients(Message.RecipientType.TO, addresses);
            message.setSubject(maildata.getSubject());
            message.setText(maildata.getContent());

            transport.sendMessage(message, addresses);
            System.out.println("SEND");
            transport.close();

            return true;
        } catch (Exception e) {
            System.out.println("FAIL");
        }
        return false;
    }
}